Vue.component('admin-product-management', {
  data() {
    return {
      products: [],
      loading: false,
      searchForm: {
        search: '',
        category_id: '',
        supplier_id: ''
      },
      dialogVisible: false,
      dialogTitle: '',
      formData: {
        id: null,
        name: '',
        sku: '',
        category_id: '',
        supplier_id: '',
        unit_price: '',
        cost_price: '',
        unit: '个',
        min_stock: 0,
        max_stock: 1000,
        description: '',
        image: ''
      },
      formRules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        sku: [
          { required: true, message: '请输入商品编码', trigger: 'blur' }
        ],
        category_id: [
          { required: true, message: '请选择商品分类', trigger: 'change' }
        ],
        supplier_id: [
          { required: true, message: '请选择供应商', trigger: 'change' }
        ],
        unit_price: [
          { required: true, message: '请输入价格', trigger: 'blur' },
          { type: 'number', message: '价格必须为数字', trigger: 'blur' }
        ],
        cost_price: [
          { required: true, message: '请输入成本', trigger: 'blur' },
          { type: 'number', message: '成本必须为数字', trigger: 'blur' }
        ],
        unit: [
          { required: true, message: '请输入单位', trigger: 'blur' }
        ]
      },
      categories: [
        { value: 'electronics', label: '电子产品' },
        { value: 'clothing', label: '服装' },
        { value: 'food', label: '食品' },
        { value: 'books', label: '图书' },
        { value: 'home', label: '家居用品' },
        { value: 'sports', label: '运动用品' }
      ],
      suppliers: [],
      currentPage: 1,
      pageSize: 10,
      total: 0
    };
  },
  methods: {
    async loadProducts() {
      this.loading = true;
      try {
        const params = {
          page: this.currentPage,
          page_size: this.pageSize,
          ...this.searchForm
        };
        const response = await productAPI.getProducts(params);
        console.log('商品API响应:', response);
        this.products = response.data.products;
        this.total = response.data.pagination.total;
        console.log('商品数据已设置:', this.products);
      } catch (error) {
        console.error('获取商品列表失败:', error);
        this.$message.error(error.message || '获取商品列表失败');
      } finally {
        this.loading = false;
      }
    },
    async loadSuppliers() {
      try {
        const response = await supplierAPI.getSuppliers();
        console.log('供应商API响应:', response);
        this.suppliers = response.data.suppliers.map(supplier => ({
          value: supplier.id,
          label: supplier.name
        }));
        console.log('供应商数据已设置:', this.suppliers);
      } catch (error) {
        console.error('获取供应商列表失败:', error);
        this.$message.error(error.message || '获取供应商列表失败');
      }
    },
    async loadCategories() {
      try {
        const response = await categoryAPI.getCategoryTree();
        console.log('分类树API响应:', response);
        this.categories = this.buildCategoryOptions(response.data);
        console.log('分类树数据已设置:', this.categories);
      } catch (error) {
        console.error('获取分类树失败:', error);
        this.$message.error(error.message || '获取分类树失败');
      }
    },
    buildCategoryOptions(categories, level = 0) {
      let options = [];
      categories.forEach(category => {
        const prefix = '　'.repeat(level);
        options.push({
          value: category.id,
          label: prefix + category.name
        });
        if (category.children && category.children.length > 0) {
          options = options.concat(this.buildCategoryOptions(category.children, level + 1));
        }
      });
      return options;
    },
    handleSearch() {
      this.currentPage = 1;
      this.loadProducts();
    },
    handleReset() {
      this.searchForm = {
        search: '',
        category_id: '',
        supplier_id: ''
      };
      this.currentPage = 1;
      this.loadProducts();
    },
    handleAdd() {
      this.dialogTitle = '添加商品';
      this.formData = {
        id: null,
        name: '',
        sku: '',
        category_id: '',
        supplier_id: '',
        unit_price: '',
        cost_price: '',
        unit: '个',
        min_stock: 0,
        max_stock: 1000,
        description: '',
        image: ''
      };
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.dialogTitle = '编辑商品';
      this.formData = { ...row };
      this.dialogVisible = true;
    },
    async handleDelete(row) {
      try {
        await this.$confirm('确定要删除这个商品吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        await productAPI.deleteProduct(row.id);
        this.$message.success('删除成功');
        this.loadProducts();
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除商品失败:', error);
          this.$message.error(error.message || '删除商品失败');
        }
      }
    },
    async handleSubmit() {
      try {
        await this.$refs.form.validate();
        
        if (this.formData.id) {
          await productAPI.updateProduct(this.formData.id, this.formData);
          this.$message.success('更新成功');
        } else {
          await productAPI.createProduct(this.formData);
          this.$message.success('添加成功');
        }
        
        this.dialogVisible = false;
        this.loadProducts();
      } catch (error) {
        console.error('保存商品失败:', error);
        this.$message.error(error.message || '保存商品失败');
      }
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.loadProducts();
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.loadProducts();
    }
  },
  async mounted() {
    console.log('ProductManagement组件已挂载');
    console.log('初始数据状态:', {
      products: this.products,
      suppliers: this.suppliers,
      categories: this.categories
    });
    
    await Promise.all([
      this.loadSuppliers(),
      this.loadCategories(),
      this.loadProducts()
    ]);
    
    console.log('数据加载完成后的状态:', {
      products: this.products,
      suppliers: this.suppliers,
      categories: this.categories
    });
  },
  template: `
    <div class="product-management">
      <el-card>
        <div slot="header">
          <span>商品管理</span>
          <el-button type="primary" icon="el-icon-plus" @click="handleAdd" style="float: right;" size="small">
            添加商品
          </el-button>
        </div>
        
        <!-- 搜索表单 -->
        <el-form :model="searchForm" inline>
          <el-form-item label="商品名称">
            <el-input v-model="searchForm.search" placeholder="请输入商品名称" clearable size="small"></el-input>
          </el-form-item>
          <el-form-item label="商品分类">
            <el-select v-model="searchForm.category_id" placeholder="请选择分类" clearable size="small">
              <el-option
                v-for="item in categories"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="供应商">
            <el-select v-model="searchForm.supplier_id" placeholder="请选择供应商" clearable size="small">
              <el-option
                v-for="item in suppliers"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleSearch" size="small">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="handleReset" size="small">重置</el-button>
          </el-form-item>
        </el-form>
        
        <!-- 商品表格 -->
        <el-table :data="products" v-loading="loading" border>
          <el-table-column prop="name" label="商品名称" min-width="150"></el-table-column>
          <el-table-column prop="sku" label="商品编码" width="150"></el-table-column>
          <el-table-column prop="category_name" label="分类" width="120"></el-table-column>
          <el-table-column prop="supplier_name" label="供应商" width="120"></el-table-column>
          <el-table-column prop="unit" label="单位" width="80"></el-table-column>
          <el-table-column prop="cost_price" label="成本" width="100">
            <template slot-scope="scope">
              ¥{{ Number(scope.row.cost_price).toLocaleString() }}
            </template>
          </el-table-column>
          <el-table-column prop="unit_price" label="价格" width="100">
            <template slot-scope="scope">
              ¥{{ Number(scope.row.unit_price).toLocaleString() }}
            </template>
          </el-table-column>
          
          <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip></el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="text" style="color: #f56c6c;" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="margin-top: 20px; text-align: right;">
        </el-pagination>
      </el-card>
      
      <!-- 添加/编辑对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px">
        <el-form :model="formData" :rules="formRules" ref="form" label-width="100px">
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入商品名称"></el-input>
          </el-form-item>
          <el-form-item label="商品编码" prop="sku">
            <el-input v-model="formData.sku" placeholder="请输入商品编码，如：PROD-001"></el-input>
          </el-form-item>
          <el-form-item label="商品分类" prop="category_id">
            <el-select v-model="formData.category_id" placeholder="请选择分类" style="width: 100%;">
              <el-option
                v-for="item in categories"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="供应商" prop="supplier_id">
            <el-select v-model="formData.supplier_id" placeholder="请选择供应商" style="width: 100%;">
              <el-option
                v-for="item in suppliers"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="成本" prop="cost_price">
            <el-input-number v-model="formData.cost_price" :precision="2" :min="0" style="width: 100%;"></el-input-number>
          </el-form-item>
          <el-form-item label="价格" prop="unit_price">
            <el-input-number v-model="formData.unit_price" :precision="2" :min="0" style="width: 100%;"></el-input-number>
          </el-form-item>
          <el-form-item label="单位" prop="unit">
            <el-input v-model="formData.unit" placeholder="请输入单位，如：个、件、台、箱"></el-input>
          </el-form-item>
          <el-form-item label="最小库存">
            <el-input-number v-model="formData.min_stock" :min="0" style="width: 100%;"></el-input-number>
          </el-form-item>
          <el-form-item label="最大库存">
            <el-input-number v-model="formData.max_stock" :min="0" style="width: 100%;"></el-input-number>
          </el-form-item>
          <el-form-item label="描述">
            <el-input type="textarea" v-model="formData.description" :rows="3" placeholder="请输入商品描述"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </el-dialog>
    </div>
  `
});
